package cn.iscorpio;

import java.util.Queue;
import java.util.Random;
import java.util.concurrent.LinkedBlockingQueue;

public class MQ {

    static Queue<Integer> queue = new LinkedBlockingQueue<>(8);
    static Random random = new Random();

    public static void main(String[] args) {
        new Thread(() -> {
            for (int i = 0; i < 100; i++) {
                queue.add(random.nextInt());
                try {
                    Thread.sleep(500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, "pub").start();

        new Thread(() -> {
            while (true) {
                synchronized (MQ.class) {
                    while (!queue.isEmpty()) {
                        String name = Thread.currentThread().getName();
                        System.out.println("thread name:" + name + ", element:" + queue.poll());
                    }
                }
            }
        }, "sub1").start();

        new Thread(() -> {
            while (true) {
                synchronized (MQ.class) {
                    while (!queue.isEmpty()) {
                        String name = Thread.currentThread().getName();
                        System.out.println("thread name:" + name + ", element:" + queue.poll());
                    }
                }
            }
        }, "sub2").start();

        new Thread(() -> {
            while (true) {
                synchronized (MQ.class) {
                    while (!queue.isEmpty()) {
                        String name = Thread.currentThread().getName();
                        System.out.println("thread name:" + name + ", element:" + queue.poll());
                    }
                }
            }
        }, "sub3").start();
    }

}
